package com.gotloop.util;

import java.text.Normalizer;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.google.appengine.repackaged.com.google.common.base.Strings;
/**
 * Utility class to transform a Title to URL Format.
 * @author jibhaine
 *
 */
public final class TitleToUrl {

	/**
	 * Logger for TitleToUrlTest.
	 */
	private static final Logger LOG = LoggerFactory.getLogger(TitleToUrl.class);

	/**
	 * Characters to be removed from the String.
	 */
	private static final String CHARS_TO_REMOVE = ",=:;+$*/\\|()[]{}#&§µ£$¤%!?^~´`¨°'’“”¿¡\"";

	/**
	 * Characters to be replaced in the String.
	 *//*
	private static final char[][] CHARS_TO_REPLACE = {{'ç', 'c'}, {'@', 'a'}, {'a', 'a'}};
	  */
	/**
	 * Characters to replace with an underscore.
	 */
	private static final String CHARS_TO_SPACE = " _-.";

	/**
	 * Private constructor.
	 */
	private TitleToUrl() {

	}

	/**
	 * Transform the String to an URL title.
	 * @param input	the Input String
	 * @return	the encoded URL
	 */
	public static String transform(String input) {
		String url = Strings.nullToEmpty(input);
		LOG.debug("input [" + url + "]");
		try {
			//remove accents
			url = Normalizer.normalize(url, Normalizer.Form.NFKD);
			LOG.trace("after normalize [" + url + "]");

			StringBuffer sBuffer = new StringBuffer();
			for (char c : url.toCharArray()) {
				//log.debug("character '" + c + "' is of type " + Character.getType(c));
				if (Character.getType(c) != Character.NON_SPACING_MARK) {
					sBuffer.append(c);
				}
			}
			url = sBuffer.toString();
			LOG.trace("removed accents [" + url + "]");

			//remove special characters
			char[] chars = CHARS_TO_REMOVE.toCharArray();
			for (char c : chars) {
				url = url.replace(Character.toString(c), "");
			}
			LOG.trace("char to remove [" + url + "]");
			//replace multiple space by one.
			while (url.contains("  ")) {
				url = url.replaceAll("  ", " ");
			}
			url = url.trim();
			LOG.trace("trim all whitespace [" + url + "]");

			//replace spacing characters with accents.
			chars = CHARS_TO_SPACE.toCharArray();
			for (char c : chars) {
				url = url.replace(Character.toString(c), "-");
			}
			LOG.trace("char to underscore [" + url + "]");
			url = StringUtils.uncapitalize(url);
			LOG.trace("after uncapitalize [" + url + "]");

			url = url.substring(0, DataConstants.URL_MAX_SIZE);
		} catch (Exception e) {
			LOG.error(e.getLocalizedMessage());
		}
		LOG.debug("output [" + url + "]");
		return url;
	}
}
